package com.example.anni.zhuzhoujia.bogege;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.anni.zhuzhoujia.R;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 张钧博 on 2016/6/4.
 * <p/>
 * 用viewSwitch更好
 */
public class SpecialSeeNewsTypeActivity extends AppCompatActivity {

    private View rootView;//缓存Fragment view

    private ImageView[] imageViews = new ImageView[4];
    private int[] ids = {
            R.id.icon1,
            R.id.icon2,
            R.id.icon3,
            R.id.icon4
    };
    private TextView tvTitle;
    private ListView lvNews;
    private ViewPager vpHead;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hot_fragment2);
        x.view().inject(this);

        lvNews = (ListView) findViewById(R.id.lv_news);

        readData();
    }

    /**
     * 读取远程数据
     */
    private void readData() {
        //有时候用Intent intent获取不到数据
        //Intent intent=new Intent();
        //此时要用getIntent
        String newstypeId = getIntent().getStringExtra("newstypeId");
        //Toast.makeText(SpecialSeeNewsTypeActivity.this, newstypeId, Toast.LENGTH_SHORT).show();

        RequestParams params = new RequestParams(
                "http://tr.zzapi.gson.cn/api/subject/news?sid=" + newstypeId + "");
        params.addBodyParameter("username", "账号");
        params.addBodyParameter("password", "密码");
        x.http().get(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String s) {
                final List<Map<String, Object>> list = new ArrayList<>();
                JSONObject jsonObject = JSON.parseObject(s);
                JSONArray data = jsonObject.getJSONArray("data");

                for (int i = 0; i < data.size(); i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    JSONObject object = data.getJSONObject(i);
                    String newsTitle = object.getString("title");
                    String newsSunmmary = object.getString("summary");
                    String newsCommentNum = object.getString("commentNum");
                    String newsCover = object.getString("cover");
                    String newsId = object.getInteger("id") + "";

                    map.put("newsTitle", newsTitle);
                    map.put("newsSunmmary", newsSunmmary);
                    map.put("newsCommentNum", newsCommentNum);
                    map.put("newsCover", newsCover);
                    map.put("newsId", newsId);

                    //Toast.makeText(getActivity(), newsTitle, Toast.LENGTH_SHORT).show();
                    list.add(map);
                }

                /*listview适配器*/
                class HotLvAdapter extends BaseAdapter {

                    @Override
                    public int getCount() {
                        return list.size();
                    }

                    @Override
                    public Object getItem(int position) {
                        return list.get(position);
                    }

                    @Override
                    public long getItemId(int position) {
                        return 0;
                    }

                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View root = getLayoutInflater().inflate(R.layout.list_item, null);

                        ImageView newsCover = (ImageView) root.findViewById(R.id.news_cover);
                        TextView newsTitle1 = (TextView) root.findViewById(R.id.news_title);
                        TextView tvSummary = (TextView) root.findViewById(R.id.tv_sunmmary);
                        TextView tvCommentnum = (TextView) root.findViewById(R.id.tv_commentnum);

                        newsTitle1.setText((String) list.get(position).get("newsTitle"));
                        tvSummary.setText((String) list.get(position).get("newsSunmmary"));
                        tvCommentnum.setText((String) list.get(position).get("newsCommentNum") + "跟帖");


                        /**
                         * 设置加载图片时等待的图片和失败的图片
                         */
                        ImageOptions options = new ImageOptions.Builder()
                                .setLoadingDrawableId(R.mipmap.ic_launcher)
                                .setFailureDrawableId(R.mipmap.broke_sel)
                                .build();

                        x.image().bind(newsCover, "http://tr.zzapi.gson.cn/" + (String) list.get(position).get("newsCover"), options);

                        if (list.get(position).get("newsCover").equals("")) {
                            newsCover.setVisibility(View.GONE);
                        } else {
                            newsCover.setVisibility(View.VISIBLE);
                        }

                        return root;
                    }
                }

                /**
                 * listview列表项的点击事件（进入新闻页）
                 */
                lvNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(SpecialSeeNewsTypeActivity.this, SeeNewsActivity.class);
                        intent.putExtra("newsId", (CharSequence) list.get(position).get("newsId"));
                        startActivity(intent);
                    }
                });

                //添加表头
                View lvHead = getLayoutInflater().inflate(R.layout.lv_head, null);
                vpHead = (ViewPager) lvHead.findViewById(R.id.vp_head);

                for (int i = 0; i < ids.length; i++) {
                    imageViews[i] = (ImageView) lvHead.findViewById(ids[i]);
                }
                tvTitle = (TextView) lvHead.findViewById(R.id.tv_title);
                tvTitle.setText((CharSequence) list.get(0).get("tvTitle"));

                //vpHead.addOnPageChangeListener(new Listener());
                //lvNews.addHeaderView(lvHead);


                lvNews.setAdapter(new HotLvAdapter());


            }

            @Override
            public void onError(Throwable throwable, boolean b) {
                //Toast.makeText(SpecialSeeNewsTypeActivity.this, "", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

}
